package com.platform.usercenter.dataprocessing;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.platform.common.core.domain.entity.SysRole;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.DateUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.constants.SysUserConstants;
import com.platform.usercenter.dataprocessing.dto.*;
import com.platform.usercenter.domain.*;
import com.platform.usercenter.domain.dto.SelectOptionDTO;
import com.platform.usercenter.mapper.DataProcessingMapper;
import com.platform.usercenter.mapper.SysOrganizationDeptMapper;
import com.platform.usercenter.mapper.SysOrganizationMapper;
import com.platform.usercenter.mapper.SysOrganizationRelationMapper;
import com.platform.usercenter.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 用户体系数据处理接口
 * @Author: wcs
 * @Date: 2024-09-22 16:06
 **/
@Slf4j
@RestController
@RequestMapping("/dataProcessing")
public class DataProcessingController {

    @Resource
    private DataProcessingMapper dataProcessingMapper;

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private SysOrganizationRelationMapper organizationRelationMapper;

    @Resource
    private SysOrganizationDeptMapper deptMapper;

    @Resource
    private SysAppPermissionMapper appPermissionMapper;

    @Resource
    private SysOrganizationPermissionMapper organizationPermissionMapper;


    private static final Integer STEP = 500;

    /**
     * 缓存新的角色组织关系
     */
    Map<String, Long> newRoleOrgMap = new HashMap<>();

    List<String> agentRoleNames = Lists.newArrayList("国际货代", "国际货代(有财务权限)", "货代前置仓", "国内货代", "国内货代（有财务权限）");

    Map<Long, AgentOrgInfoDTO> agentOrgInfoDTOMap = new HashMap<>();

    /**
     * 所有数据的处理脚本--测试
     */
    @GetMapping("/myTest")
    public void myTest() {

        // 1、用户体系表结构更新
        // 2、应用场景（包括key配置）
        // 3、菜单应用场景
        // 4、组织（包括货代）
        // 5、组织应用场景关系
        // 6、组织应用权限
        // 7、用户数据（用户组织绑定）
        // 8、用户组织关联
        // 9、用户部门关联
        // 10、角色（包括角色组织关系）
        // 11、角色菜单关系
        // 12、角色应用权限
        // 13、角色用户关系
        long start = System.currentTimeMillis();
        delUserInfo();
        preRoleHandler();
        userRole();
        renameTable();
        updateData();
        log.info("总计耗时为:{}秒", (System.currentTimeMillis() - start) / 1000);
    }

    private void updateData() {
        dataProcessingMapper.executeSql("INSERT INTO sys_role_menu (role_id, menu_id, org_id, is_delete)\n" +
                "SELECT DISTINCT role_id, 4 AS menu_id, org_id, 'N' AS is_delete\n" +
                "FROM sys_role_menu");

        dataProcessingMapper.executeSql("INSERT INTO sys_role_menu (role_id, menu_id, org_id, is_delete)\n" +
                "SELECT DISTINCT role_id, 5 AS menu_id, org_id, 'N' AS is_delete\n" +
                "FROM sys_role_menu");

        dataProcessingMapper.executeSql("INSERT INTO sys_role_menu (role_id, menu_id, org_id, is_delete)\n" +
                "SELECT DISTINCT role_id, 6 AS menu_id, org_id, 'N' AS is_delete\n" +
                "FROM sys_role_menu");
    }

    private void renameTable() {
        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_role","sys_role_tmp"));
        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_role_new","sys_role"));

        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_role_menu","sys_role_menu_tmp"));
        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_role_menu_new","sys_role_menu"));

        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_user_role","sys_user_role_tmp"));
        dataProcessingMapper.executeSql(String.format(SqlConstant.RENAME_TABLE,"sys_user_role_new","sys_user_role"));
    }

    public void preRoleHandler() {
        // 全局变量清空
        agentOrgInfoDTOMap.clear();
        newRoleOrgMap.clear();
        // 菜单数据初始化
        // 货代权限映射表初始化
        // 新建表
        createNewTableFromTable("sys_role_new", "sys_role");
        createNewTableFromTable("sys_role_menu_new", "sys_role_menu");
        createNewTableFromTable("sys_user_role_new", "sys_user_role");
        // 主键处理
        dataProcessingMapper.executeSql("ALTER TABLE `sys_user_role_new` DROP PRIMARY KEY");
        log.info("角色处理预先配置完成");
    }

    private void createNewTableFromTable(String newTableName, String fromTableName) {
        String dropSql = String.format(SqlConstant.DROP_TABLE_IF_EXISTS, newTableName);
        log.info("删除语句:{}", dropSql);
        dataProcessingMapper.executeSql(dropSql);
        String creatSql = String.format(SqlConstant.CREATE_TABLE_LIKE, newTableName, fromTableName);
        log.info("创建语句:{}", creatSql);
        dataProcessingMapper.executeSql(creatSql);
    }

    public void userRole() {
        List<String> normalDeptNames = Lists.newArrayList("集团", "航发公司");
        List<String> outRoleNames = Lists.newArrayList("外包巡检管理员", "外包巡查员");
        List<UserOrgDTO> userOrgList = dataProcessingMapper.selectUserOrg();
        // 按照用户组织处理角色数据
        List<SysUserRole> saveData = Lists.newArrayList();
        for (UserOrgDTO userOrgDTO : userOrgList) {
            List<SysRole> roles = dataProcessingMapper.selectUserRole(userOrgDTO.getUserId());
            for (SysRole role : roles) {
                Pair<Long, Long> pair;
                if (outRoleNames.contains(role.getRoleName()) && "外包巡检单位".equals(userOrgDTO.getDeptName())) {
                    pair = orgRole(role.getRoleName(), userOrgDTO.getOrgId());
                } else if (agentRoleNames.contains(role.getRoleName()) && "货代公司".equals(userOrgDTO.getDeptName())) {
                    pair = orgRole(role.getRoleName(), userOrgDTO.getOrgId());
                } else if ("报关公司".equals(userOrgDTO.getDeptName())) {
                    pair = orgRole(role.getRoleName(), userOrgDTO.getOrgId());
                } else if (normalDeptNames.contains(userOrgDTO.getDeptName()) && !agentRoleNames.contains(role.getRoleName())) {
                    pair = orgRole(role.getRoleName(), userOrgDTO.getOrgId());
                } else {
                    continue;
                }
                saveData.add(getSysUserRole(pair, userOrgDTO));
            }
        }
        dataProcessingMapper.batchInsertSyUserRole(saveData);
        log.info("角色数据处理完成");
    }

    private SysUserRole getSysUserRole(Pair<Long, Long> pair, UserOrgDTO userOrgDTO) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setOrgId(pair.getLeft());
        sysUserRole.setIsDelete("N");
        sysUserRole.setUserId(userOrgDTO.getUserId());
        sysUserRole.setRoleId(pair.getRight());
        sysUserRole.setDeptId(userOrgDTO.getOldDeptId());
        sysUserRole.setCreateBy("数据刷新");
        sysUserRole.setCreateTime(new Date());
        sysUserRole.setRemark("数据初始化");
        return sysUserRole;
    }

    public Pair<Long, Long> orgRole(String roleName, Long destOrgId) {
        String key = String.join("#", roleName, String.valueOf(destOrgId));
        // 先查询该组织下是否有该角色 有直接返回
        Long roleId = newRoleOrgMap.get(key);
        if (Objects.nonNull(roleId)) {
            return Pair.of(destOrgId, roleId);
        }
        List<SysRole> roles = dataProcessingMapper.selectRoleFromNewTable(roleName, destOrgId);
        if (roles.size() == 1) {
            SysRole sysRole = roles.get(0);
            newRoleOrgMap.put(key, sysRole.getRoleId());
            return Pair.of(destOrgId, sysRole.getRoleId());
        } else if (CollectionUtil.isEmpty(roles)) {
            SysRole newRole;
            // 如果是货代角色 没有则直接复制
            newRole = dataProcessingMapper.selectRoleFromOldRole(roleName);
            Long oldRoleId = newRole.getRoleId();
            newRole.setOrgId(destOrgId);
            newRole.setRoleFlag("0");
            dataProcessingMapper.insertNewRole(newRole);
            log.info("新插入的角色为:{}", JSON.toJSONString(newRole));
            // 查询角色菜单关系
            List<SysRoleMenu> roleMenus = dataProcessingMapper.selectRoleMenuOld(oldRoleId);
            List<SysRoleMenu> saveRoleMenus = Lists.newArrayList();
            List<SysRoleMenu> newRoleMenus;
            if (agentRoleNames.contains(roleName)) {
                Set<Long> oldMenuIds = roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
                List<AgentMenuMappingDTO> mappings = dataProcessingMapper.selectAgentMenuMapping(oldMenuIds);
                Map<Long, AgentMenuMappingDTO> map = mappings.stream().collect(Collectors.toMap(AgentMenuMappingDTO::getOldMenuId, value -> value));
                // 先清理
                List<Long> needDel = mappings.stream()
                        .flatMap(item -> {
                            if (StringUtils.isNotBlank(item.getOldMenuChildren())) {
                                return Arrays.stream(item.getOldMenuChildren().split(","))
                                        .map(s -> Optional.of(s.trim())
                                                .filter(t -> !t.isEmpty())
                                                .map(Long::parseLong)
                                                .orElse(null))
                                        .filter(Objects::nonNull);
                            } else {
                                return Stream.empty();  // 返回一个空流
                            }
                        })
                        .collect(Collectors.toList());
                roleMenus = roleMenus.stream().filter(item -> !needDel.contains(item.getMenuId())).collect(Collectors.toList());
                // 交换菜单id 换成货代的
                roleMenus.forEach(item -> {
                    item.setOrgId(destOrgId);
                    item.setRoleId(newRole.getRoleId());
                    AgentMenuMappingDTO agentMenuMapping = map.get(item.getMenuId());
                    if (Objects.nonNull(agentMenuMapping)) {
                        item.setMenuId(agentMenuMapping.getAgentMenuId());
                        saveRoleMenus.add(item);
                        // 默认货代的全部菜单复制
                        List<SysRoleMenu> buttons = generateButton(agentMenuMapping.getAgentMenuChildren(), destOrgId, newRole.getRoleId());
                        saveRoleMenus.addAll(buttons);
                    } else {
                        saveRoleMenus.add(item);
                    }
                });
                dataProcessingMapper.batchInsetNewSysRoleMenu(saveRoleMenus);
                newRoleMenus = saveRoleMenus;
            } else {
                // 其他角色查询数据平移
                roleMenus.forEach(item -> {
                    item.setRoleId(newRole.getRoleId());
                    item.setOrgId(destOrgId);
                });
                List<Long> filterMenuIds = Lists.newArrayList(2967L, 2972L, 3262L, 3263L, 3265L);
                roleMenus = roleMenus.stream().filter(item -> !filterMenuIds.contains(item.getMenuId())).collect(Collectors.toList());
                dataProcessingMapper.batchInsetNewSysRoleMenu(roleMenus);
                newRoleMenus = roleMenus;
            }
            newRoleOrgMap.put(key, newRole.getRoleId());
            // 根据角色创建数据权限
            createMenuValue(newRoleMenus, destOrgId, newRole);
            return Pair.of(destOrgId, newRole.getRoleId());
        } else {
            throw new ServiceException("新的角色表数据存在问题,同组织,同角色名称超过1条");
        }
    }

    private void createMenuValue(List<SysRoleMenu> newRoleMenus, Long destOrgId, SysRole newRole) {
        Set<Long> menuIds = newRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
        // 查询应用场景与key数据
        if (CollectionUtil.isEmpty(agentOrgInfoDTOMap)) {
            List<AgentOrgInfoDTO> list = dataProcessingMapper.selectAgentInfoMap();
            agentOrgInfoDTOMap = list.stream().collect(Collectors.toMap(AgentOrgInfoDTO::getOrgId, value -> value));
        }
        List<AppScenePermissionDTO> list = dataProcessingMapper.selectAppSceneAndPermission(menuIds);
        List<SysRoleMenuValue> savaData = list.stream().map(item -> {
            SysRoleMenuValue value = new SysRoleMenuValue();
            value.setAppSceneId(item.getAppSceneId());
            value.setOrgId(destOrgId);
            value.setRoleId(newRole.getRoleId());
            value.setPermissionId(item.getPermissionId());
            value.setCode(item.getCode());
            value.setIsDelete("N");
            value.setCreateBy("数据初始化");
            value.setCreateTime(new Date());
            value.setRemark("数据初始化");
            if (StringUtils.equals("DP_AGENT_CODE", item.getCode())) {
                AgentOrgInfoDTO agentOrgInfoDTO = agentOrgInfoDTOMap.get(destOrgId);
                if (Objects.isNull(agentOrgInfoDTO)) {
                    log.info("货代不存在:orgId" + Math.toIntExact(destOrgId));
                    throw new ServiceException("货代不存在:orgId" + Math.toIntExact(destOrgId));
                } else {
                    SelectOptionDTO option = new SelectOptionDTO();
                    option.setLabel(agentOrgInfoDTO.getOrgName());
                    option.setValue(agentOrgInfoDTO.getAgentCode());
                    value.setValue(JSON.toJSONString(Lists.newArrayList(option)));
                }
            } else {
                value.setValue(getValueStrByCode(item.getCode()));
            }
            return value;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(savaData)) {
            dataProcessingMapper.batchInsertRoleMenuValue(savaData);
        }

    }

    private String getValueStrByCode(String code) {
        SelectOptionDTO option = new SelectOptionDTO();
        switch (code) {
            case "DP_AIRPORT_CODE":
                option.setValue("NNG");
                option.setLabel("南宁");
                return JSON.toJSONString(Lists.newArrayList(option));
            case "DP_TENANT_CODE":
                option.setValue("TC20241122162235000003");
                option.setLabel("南宁货站");
                return JSON.toJSONString(Lists.newArrayList(option));
            case "DP_MERCHANT_NO":
                option.setValue("M1698202459");
                option.setLabel("广西民航产业发展有限公司南宁航空物流分公司");
                return JSON.toJSONString(Lists.newArrayList(option));
            case "DP_TAX_NO":
                option.setValue("91450100581984254N");
                option.setLabel("广西民航产业发展有限公司南宁航空物流分公司");
                return JSON.toJSONString(Lists.newArrayList(option));
            case "DP_AGENT_CODE":
                option.setValue("待定");
                option.setLabel("待定");
                return JSON.toJSONString(Lists.newArrayList(option));
        }
        return null;
    }

    private List<SysRoleMenu> generateButton(String agentMenuChildren, Long destOrgId, Long roleId) {
        if (StringUtils.isBlank(agentMenuChildren)) {
            return Lists.newArrayList();
        }
        return Arrays.stream(agentMenuChildren.split(","))
                .map(s -> Optional.of(s.trim())
                        .filter(t -> !t.isEmpty())
                        .map(Long::parseLong)
                        .orElse(null))
                .filter(Objects::nonNull).map(item -> {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setOrgId(destOrgId);
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(item);
                    return sysRoleMenu;
                }).collect(Collectors.toList());
    }

    public void getApplicationData() {
        List<SysOrganization> relations = selectRangeByTableName("sys_organization",
                SysOrganization.class, Pair.of(0, 100));

        List<SysOrganization> feeItems = selectRangeByTableName("sys_organization", SysOrganization.class, Pair.of(0, 100));
        Map<Long, SysOrganization> organizationMap = feeItems.stream().collect(Collectors.toMap(SysOrganization::getOrgId, value -> value));

        log.info("处理结束{}", JSON.toJSONString(organizationMap));
    }

    /**
     * 所有数据的处理脚本
     */
    @GetMapping("/dataProcessAll")
    public void dataProcessAll() throws Exception {
        long start = System.currentTimeMillis();
        // 清空所有新表
//        truncateTableAllTable();
        // 组织应用绑定
        orgAppProcessing();

        log.info("数据处理总计耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
    }

    /**
     * 货代组织应用绑定--基于组织信息刷完
     */
    private void orgAppProcessing() {
        List<SysOrganizationDateDTO> organizations = selectRangeByTableName("sys_organization", SysOrganizationDateDTO.class, Pair.of(0, 500));
        if (CollectionUtil.isNotEmpty(organizations)) {
            List<SysOrganizationDateDTO> agentOrgs = organizations.stream().filter(item -> StringUtils.isNotEmpty(item.getAgentCode())).collect(Collectors.toList());
            for (SysOrganizationDateDTO organization : agentOrgs) {


            }
        }
    }

    public void delUserInfo() {
        long start = System.currentTimeMillis();
        orgProcessing();// 刷新组织数据
        flushOrgDept();// 刷新组织部门表数据
        dealUserOrg();// 处理用户组织部门关联关系
        delUserDefaultOrg();// 处理用户默认组织信息
        orgAppPreProcessing();// 处理组织应用权限关联关系
        log.info("数据处理处理完毕,耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
    }

    /**
     * 刷新组织数据
     */
    private void orgProcessing() {
        List<SysOrganizationDateDTO> organizationDTOS = dataProcessingMapper.getOrgList();
        for (SysOrganizationDateDTO dateDTO : organizationDTOS) {
            dateDTO.setCreateBy("数据刷新");
            dateDTO.setCreateTime(DateUtils.getNowDate());
            dataProcessingMapper.insertSysOrganization(dateDTO);
        }
    }

    /**
     * 刷新组织部门表数据
     */
    private void flushOrgDept() {
        List<SysOrganizationDept> deptDTOS = dataProcessingMapper.getOrgDeptList();
        for (SysOrganizationDept dateDTO : deptDTOS) {
            dataProcessingMapper.insertSysOrganizationDept(dateDTO);
        }
    }


    /**
     * 处理用户组织部门关联关系
     */
    private void dealUserOrg() {
        List<SysOrgDeptUserDTO> userOrgDeptList = dataProcessingMapper.getUserOrgDeptList();
        for (SysOrgDeptUserDTO userDTO : userOrgDeptList) {
            userDTO.setCreateBy("数据刷新");
            userDTO.setCreateTime(DateUtils.getNowDate());
            dataProcessingMapper.insertSysOrgDeptUser(userDTO);
        }
    }

    /**
     * 处理用户默认组织信息
     */
    private void delUserDefaultOrg() {
        dataProcessingMapper.delUserDefaultOrg();
    }

    /**
     * 处理岗位信息
     */
    private void dealDeptPost() {

    }


    /**
     * 组织应用权限绑定
     */
    private void orgAppPreProcessing() {
        SysAppPermission query = new SysAppPermission();
        query.setIsDelete(SysUserConstants.N);
        List<SysAppPermission> appPermissions=appPermissionMapper.selectSysAppPermissionList(query);
        Map<Long,List<SysAppPermission>> appMap = appPermissions.stream().collect(Collectors.groupingBy(item->item.getAppSceneId()));
        // 查询组织下全部角色
        List<SysOrgRoleDTO>  orgRoleDTOS = dataProcessingMapper.getOrgRoleList();
        if(CollectionUtil.isNotEmpty(orgRoleDTOS)){
            for (SysOrgRoleDTO orgDto : orgRoleDTOS){
                String[] roldIds = orgDto.getRoleIds().split(",");
                Long[] longArray = Stream.of(roldIds)
                        .map(Long::parseLong)
                        .toArray(Long[]::new);
                List<SysOrgRoleDTO> appDtos =  dataProcessingMapper.getOrgAppList(longArray);
                if(CollectionUtil.isNotEmpty(appDtos)){
                    for (SysOrgRoleDTO appDto : appDtos){

                        List<SysAppPermission> appPermissionList=appMap.get(appDto.getAppSceneId());
                        if(CollectionUtil.isNotEmpty(appPermissionList)){
                            for(SysAppPermission permission : appPermissionList){
                                SysOrganizationPermission orgPer = new SysOrganizationPermission();
                                orgPer.setOrgId(orgDto.getOrgId());
                                orgPer.setAppSceneId(appDto.getAppSceneId());
                                orgPer.setCode(permission.getCode());
                                if("DP_AIRPORT_CODE".equals(permission.getCode())){
                                    orgPer.setPermissionId(permission.getPermissionId());
                                    SelectOptionDTO optionDTO = new SelectOptionDTO();
                                    optionDTO.setLabel("机场");
                                    optionDTO.setValue("NNG");
                                    orgPer.setValue(JSON.toJSONString(optionDTO));
                                }else if("DP_AGENT_CODE".equals(permission.getCode())){//货代
                                    orgPer.setPermissionId(permission.getPermissionId());
                                    if(StringUtils.isNotEmpty(orgDto.getAgentCode())&&StringUtils.isNotEmpty(orgDto.getAgentName())){
                                        orgPer.setPermissionId(permission.getPermissionId());
                                        SelectOptionDTO optionDTO = new SelectOptionDTO();
                                        optionDTO.setLabel(orgDto.getAgentName());
                                        optionDTO.setValue(orgDto.getAgentCode());
                                        orgPer.setValue(JSON.toJSONString(optionDTO));
                                    }
                                }else if("DP_TAX_NO".equals(permission.getCode())){//税号
                                    orgPer.setPermissionId(permission.getPermissionId());
                                    SelectOptionDTO optionDTO = new SelectOptionDTO();
                                    optionDTO.setLabel("广西民航产业发展有限公司");
                                    optionDTO.setValue("91450000561591752B");
                                    orgPer.setValue(JSON.toJSONString(optionDTO));
                                }else if("DP_TENANT_CODE".equals(permission.getCode())){//收款方
                                    orgPer.setPermissionId(permission.getPermissionId());
                                    SelectOptionDTO optionDTO = new SelectOptionDTO();
                                    optionDTO.setLabel("南宁货站");
                                    optionDTO.setValue("TC20241122162235000003");
                                    orgPer.setValue(JSON.toJSONString(optionDTO));
                                }else if("DP_MERCHANT_NO".equals(permission.getCode())){//商户号
                                    orgPer.setPermissionId(permission.getPermissionId());
                                    SelectOptionDTO optionDTO = new SelectOptionDTO();
                                    optionDTO.setLabel("南宁航空物流分公司");
                                    optionDTO.setValue("M1713142181");
                                    orgPer.setValue(JSON.toJSONString(optionDTO));
                                }
                                orgPer.setCreateTime(new Date());
                                organizationPermissionMapper.insertSysOrganizationPermission(orgPer);
                            }
                        }else {
                            SysOrganizationPermission orgPer = new SysOrganizationPermission();
                            orgPer.setOrgId(orgDto.getOrgId());
                            orgPer.setAppSceneId(appDto.getAppSceneId());
                            orgPer.setCreateTime(new Date());
                            organizationPermissionMapper.insertSysOrganizationPermission(orgPer);
                        }
                    }
                }
            }
        }
    }


    /**
     * 清空表
     *
     * @param tableName
     */
    private void truncateTable(String tableName) {
        dataProcessingMapper.truncateTable(tableName);
    }


    private <T> List<T> selectRangeByTableName(String tableName, Class<T> clazz, Pair<Integer, Integer> pair) {
        List<T> res = Lists.newArrayList();
        List<Map<String, Object>> list = dataProcessingMapper.selectRangeDataByTableName(tableName, pair.getLeft(), pair.getRight());
        for (Map<String, Object> map : list) {
            String jsonString = JSON.toJSONString(map);
            T t = JSON.parseObject(jsonString, clazz);
            res.add(t);
        }
        return res;
    }


    private List<Pair<Integer, Integer>> getPartitionByTableName(String tableName) {
        return partition(dataProcessingMapper.selectCountByTableName(tableName));
    }

    private List<Pair<Integer, Integer>> partition(int count) {
        List<Pair<Integer, Integer>> list = Lists.newArrayList();
        if (count <= STEP) {
            list.add(Pair.of(0, count));
            return list;
        }
        int step = STEP;
        for (int i = 0; i < count; i += step) {
            list.add(Pair.of(i + 1, STEP));
        }
        return list;
    }

}
